package com.nbgroup.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.nbgroup.pojo.Dept;
import com.nbgroup.mapper.DeptMapper;
import com.nbgroup.pojo.common.Children;
import com.nbgroup.pojo.common.ChildrenWithOutChildren;
import com.nbgroup.pojo.dto.DeptDto;
import com.nbgroup.service.IDeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-10-29
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements IDeptService {

    /**
     * 部门列表查询
     * @return
     */
    @Override
    public List<Dept> listQueryDept() {
        List<Dept> list = lambdaQuery().list();
        return list;
    }

    /**
     * 新增部门
     * @param dto
     */
    @Override
    public void add(DeptDto dto) {
        Dept one = lambdaQuery().eq(Dept::getDeptId, dto.getParentId()).one();
        Dept dept = BeanUtil.copyProperties(dto, Dept.class);
        dept.setAncestors(one.getAncestors()+","+dto.getParentId());
        save(dept);
    }

    /**
     * 树查询
     * @return
     */
    @Override
    public List<Children> queryTree(Integer parentId) {
        List<Dept> list = lambdaQuery().eq(Dept::getParentId, parentId).list();
        List<Children> childrenList = BeanUtil.copyToList(list, Children.class);
        childrenList.forEach(children -> {
            List<Children> list1 = queryTree(children.getDeptId());
            children.setChildren(list1);
            if (CollectionUtils.isEmpty(list1)){
                children.setChildren(null);
                BeanUtil.copyProperties(children, ChildrenWithOutChildren.class);
            }
        });
        return childrenList;
    }
}
